export class ZipRoomPlan
{
    static offset=48;
    public static Zip(roomPlan:IModulePlan[]):string
    {
        const ziparr:any[]=[];
        for(const plan of roomPlan)
        {
            ziparr.push(this.ZipModulePlan(plan));
        }
        return JSON.stringify(ziparr);
    }
    public static Unzip(zip:string):IModulePlan[]
    {
        const ziparr:any[] = JSON.parse(zip);
        const roomPlan:IModulePlan[] = [];
        for(const plan of ziparr)
        {
            roomPlan.push(this.UnZipModulePlan(plan));
        }
        return roomPlan;
    }

    public static UnzipMap(zip:string):Record<string,IModulePlan[]>
    {
        const ziparr:any[] = JSON.parse(zip);
        
        const planMap:Record<string,IModulePlan[]>={}
        for(const plan of ziparr)
        {
            const tmpplan = this.UnZipModulePlan(plan);
            if(planMap[tmpplan.type])
            {
                planMap[tmpplan.type].push(tmpplan);
            }
            else
            {
                planMap[tmpplan.type]=[tmpplan]
            }
            
        }
        return planMap;
    }

    private static ZipModulePlan(modulePlan:IModulePlan):any
    {
        let zipobj:any = _.clone(modulePlan);
        let zipstructure:any = {};
        for(const type in modulePlan.structures)
        {
            let strposarr = "";
            for(const pso of modulePlan.structures[type])
            {
                strposarr =  strposarr.concat( this.ZipVector2D(pso))
            }
            zipstructure[type] = strposarr;
        }
        zipobj.structures = zipstructure;
        zipobj.pos = this.ZipVector2D( zipobj.pos);
        return zipobj;
    }

    private static UnZipModulePlan(modulePlan:any):IModulePlan
    {
        let structures:{[key in string]:IFVector2[]}={};
        for(const type in modulePlan.structures)
        {
            let posarr:IFVector2[] = [];

            const posarrstr =  modulePlan.structures[type];

            for(let i=0;i<posarrstr.length;i+=2)
            {
                posarr.push(this.UnZipVector2D(posarrstr.substring(i,i+2)));
            }

            structures[type] = posarr;
        }
        modulePlan.structures = structures;
        modulePlan.pos = this.UnZipVector2D(  modulePlan.pos);
        return modulePlan;
    }
    private static ZipVector2D(vector2D:IFVector2):string
    {
        return String.fromCharCode(vector2D.x+this.offset)+""+ String.fromCharCode(vector2D.y+this.offset);
    }
    private static UnZipVector2D(vector2D:string):IFVector2
    {
        return {x:vector2D.charCodeAt(0)-this.offset,y:vector2D.charCodeAt(1)-this.offset}
    }
}
